package com.nerve.android.cloudoffice.app.worker;

import static com.nerve.android.cloudoffice.app.NavigationActivity.WORKER_FAIL;
import static com.nerve.android.cloudoffice.app.NavigationActivity.WORKER_OK;

import java.util.HashMap;
import java.util.Map;

import android.os.AsyncTask;
import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.nerve.android.cloudoffice.OfficeApplication;
import com.nerve.android.cloudoffice.common.Const;
import com.nerve.android.cloudoffice.common.Reply;
import com.nerve.android.cloudoffice.domain.User;
import com.nerve.android.cloudoffice.service.NetService;

/**
 * @project: Cloudoffice
 * @file: LoginActivity.java
 * @package: com.nerve.android.cloudoffice.app.activity
 * @description:
 *
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: Aug 15, 2013
 * @change log:
 */
public class LoginWorker extends AsyncTask<String, Void, Integer>{
	
	private final String URL = Const.HOST + "login.htm?app=1";
	private Handler handler;
	
	public LoginWorker(Handler handler){
		this.handler = handler;
	}
	
	@Override
	protected Integer doInBackground(String... params) {
		if(params.length != 2)
			return WORKER_FAIL;
		
		Map<String, String> map = new HashMap<String, String>();
		map.put("name", params[0]);
		map.put("password", params[1]);
		
		Reply re = NetService.post(URL, map);
		if(re.isError())
			Const.ERROR = re.getMessage().toString();
		else{
			try{
				User user = JSON.parseObject(re.getMessage().toString(), User.class);
				OfficeApplication.login(user);
				
			}catch(Exception e){
				Const.log("解析login后的user出错：" + e);
				re.error(e);
			}
		}
		
		return re.isError()? WORKER_FAIL : WORKER_OK;
	}
	
	@Override
	protected void onPostExecute(Integer result) {
		handler.sendEmptyMessage(result);
	}
	
}